/**
    Copyright (C) 2013 Guido Ludwig

	This file is part of JATT.
	http://code.google.com/p/jatt/

    JATT is free software. You can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.guidoludwig.jatt.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;


/**
 * @author Guido Ludwig
* Utility methods that allow you to output images with the opportunity to
* specify the quality setting for the compression.
*
*/
public class ImageUtil {
	
	private static ImageWriter getWriter(String mimeType) {
		ImageWriter imageWriter;
		Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(mimeType);
		// Just get the first writer available
		imageWriter = i.next();
		if (imageWriter == null) {
			throw new IllegalArgumentException("No ImageWriter for mime type : " + mimeType);
		}
		return imageWriter;
	}
	
    private ImageUtil() {}


	public static void writeFile(BufferedImage image, String mimeType,
			File outputFile, float compressionQuality) throws FileNotFoundException, IOException {

		ImageWriter imageWriter = getWriter(mimeType);
		ImageWriteParam param = imageWriter.getDefaultWriteParam();
		if (param.canWriteCompressed()) {
			param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			param.setCompressionQuality(compressionQuality);
		}

		// Write the image to a file
		FileImageOutputStream out = new FileImageOutputStream(outputFile);
		imageWriter.setOutput(out);
		imageWriter.write(null, new IIOImage(image, null, null), param);
		imageWriter.dispose();
		out.close();
	}    
    
    
}